package com.zx.framework.core.util;

import java.util.List;

public class SQLBuilder {
	/**
	 * 追加sql语句
	 * @param clause eg:"and age=18","and sex = 1"
	 * @return
	 */
	public static String appendSQL(List<String> clause)
	{
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < clause.size(); i++)
		{
			sb.append(" "+clause.get(i)+" ");
		}
		return sb.toString();
	}
	
	/**
	 * 追加sql语句
	 * @param clause eg:"and age=18","and sex = 1"
	 * @return
	 */
	public static String appendWhereSQL(List<String> clause)
	{
		if(clause.isEmpty()){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < clause.size(); i++)
		{
			sb.append(" "+clause.get(i)+" ");
		}
		return " where 1=1 "+sb.toString();
	}
	/**
	 * 将查询条件追加到sql语句的后面
	 * @param sql
	 * @param clause 查询条件
	 * @param order 排序语句
	 * @return
	 */
	public static String appendClauses(String sql,List<String> clause,String ... orders){
		StringBuilder builder = new StringBuilder();
		builder.append(sql);
		builder.append(" ");
		builder.append(appendSQL(clause));
		builder.append(appendOrder(orders));
		return builder.toString();
	}
	
	/**
	 * 将查询条件追加到sql语句的后面
	 * @param sql
	 * @param clause 查询条件 eg:"and age=18","and sex = 1"
	 * @param order 排序语句
	 * @return
	 */
	public static String appendWhereClauses(String sql,List<String> clause,String ... orders){
		StringBuilder builder = new StringBuilder();
		builder.append(sql);
		builder.append(" where 1=1 ");
		builder.append(appendSQL(clause));
		
		appendOrder(orders);
		
		return builder.toString();
	}
	/**
	 * 添加排序
	 * @param orders eg:" age desc,sex"
	 * @return
	 */
	public static String appendOrder(String hqlOrSql,String[]  orders)
	{
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < orders.length; i++)
		{
			sb.append(" "+orders[i]+" ");
			if(i!=orders.length-1)
			{
				sb.append(",");
			}
		}
		return hqlOrSql + " order by " +sb.toString();
	}
	
	/**
	 * 添加排序
	 * @param orders eg:" age desc,sex"
	 * @return
	 */
	public static String appendOrder(String ... orders)
	{
		if(orders == null || orders.length==0){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < orders.length; i++)
		{
			sb.append(" "+orders[i]+" ");
			if(i!=orders.length-1)
			{
				sb.append(",");
			}
		}
		return " order by " +sb.toString();
	}
}
